// package_main/pages/change-nickname/index.js
const app=getApp()
Page({
  data: {
    avatarUrl:'',
    username:'',
    gender:'',
    birthday:'',
    email:'',
    openid:'',
    //表单选项
    genders:[
      {name:'男',value:'男'},
      {name:'女',value:'女'},
    ],
    genderIndex:0,
    today:new Date().toISOString().split('T')[0]//用在生日选择器
  },
  
  onLoad() {
    // 从全局变量读取数据
    const userInfo = app.globalData.tempUserInfo;
    if (userInfo) {
      this.setData({
        avatarUrl: userInfo.avatar,
        username: userInfo.username,
        gender: userInfo.gender ,
        birthday: userInfo.birthday || '',
        email: userInfo.email || '',
        openid: userInfo.openid
      });
    } else {
      wx.showToast({
        title: '未获取到用户信息',
        icon: 'none'
      });
      setTimeout(() => wx.navigateBack(), 1500);
    }
  },
  //更换头像
  changeAvatar(){
    wx.chooseMedia({
      success:async (res)=>{
        let tempFilePath=res.tempFiles[0].tempFilePath
        //上传到云端
        let uplocadRes=await wx.cloud.uploadFile({
          cloudPath:`avatars/${Date.now()}-${Math.floor(Math.random()*1000)}.png`,
          filePath: tempFilePath
        })
        this.setData({
          avatarUrl:uplocadRes.fileID
        })
      }
    })
  },
  
  // 昵称输入处理
  handleNicknameInput(ev) {
    this.setData({
      username: ev.detail.value
    })
  },
  //性别选择
  changeGender(ev){
    this.setData({
      genderIndex:ev.detail.value,
      gender:this.data.genders[ev.detail.value].value
    })
  },
  //生日选择
  chengeBirthday(ev){
    this.setData({birthday:ev.detail.value})
  },
  //邮箱
  emailInput(ev){
    this.setData({email:ev.data.value})
  },
   // 保存修改
   async saveProfile(){
     let {avatarUrl,username,gender,birthday,email,openid}=this.data
     if(!username.trim()){
       wx.showToast({title: '昵称不能为空',icon:'none'})
       return
     }
    //  if(!email.includes('@')){
    //    wx.showToast({title: '请输入有效邮箱',icon:'none'})
    //  }
     //调用云函数更新昵称
     let updateData={
      avatar:avatarUrl,
      username: username,
      gender: gender,
      birthday: birthday,
      email: email
     }
     let res=await wx.cloud.callFunction({
       name:'editUser',
       data:{
         openid:openid,
         updateData:updateData
       }
    })
    wx.showToast({title: '保存成功',icon:'success'})
         //更新本地存储
         wx.getStorage({
           key:'userinfo',
           success:(storageRes)=>{
             let userinfo=storageRes.data
             Object.assign(userinfo, updateData)
             wx.setStorage({
               key:'userinfo',
               data:userinfo
             })
             //返回上一页并传值
            
            setTimeout(()=>wx.navigateBack(),1500)
           }
       })
     },
   back(){
    wx.navigateBack({
      delta: 2
    })
    this.setData({
      avatar:avatarUrl,
      username:username
    })
  },
})